package net.sahv.bdyz.util;

import java.awt.Graphics2D;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.InputStream;

import javax.imageio.ImageIO;
/*
* pHash-like image hash. 
* Author: Elliot Shepherd (elliot@jarofworms.com
* Based On: http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html
*/
/*
 * 以图搜图范例
 * 感知哈希算法(以下简称PHA)是哈希算法的一类，主要用来做相似图片的搜索工作。

PHA是一类比较哈希方法的统称。图片所包含的特征被用来生成一组指纹(不过它不是唯一的),而这些指纹是可以进行比较的。

下面是简单的步骤，来说明对图像进行PHA的运算过程:

第一步，缩小尺寸。

最快速的去除高频和细节，只保留结构明暗的方法就是缩小尺寸。

将图片缩小到8x8的尺寸，总共64个像素。摒弃不同尺寸、比例带来的图片差异。

第二步，简化色彩。

将缩小后的图片，转为64级灰度。也就是说，所有像素点总共只有64种颜色。

第三步，计算平均值。

计算所有64个像素的灰度平均值。

第四步，比较像素的灰度。

算法的精髓，简单、有趣，又充满深意。

将每个像素的灰度，与平均值进行比较。大于或等于平均值，记为1;小于平均值，记为0。

第五步，计算哈希值。

将上一步的比较结果，组合在一起，就构成了一个64位的整数，这就是这张图片的指纹。组合的次序并不重要，只要保证所有图片都采用同样次序就行了(例如，自左到右、自顶向下、big-endian)。

得到指纹以后，就可以对比不同的图片，看看64位中有多少位是不一样的。在理论上，这等同于计算Hammingdistance)。如果不相同的数据位不超过5，就说明两张图片很相似;如果大于10，就说明这是两张不同的图片。

 * 
 * 王聪朝 2016年5月28日14:12:58
 */
public class ImagePHash {

   private int size = 32;
   private int smallerSize = 8;
   
   public ImagePHash() {
       initCoefficients();
   }
   
   public ImagePHash(int size, int smallerSize) {
       this.size = size;
       this.smallerSize = smallerSize;
       
       initCoefficients();
   }
   
   public int distance(String s1, String s2) {
       int counter = 0;
       for (int k = 0; k < s1.length();k++) {
           if(s1.charAt(k) != s2.charAt(k)) {
               counter++;
           }
       }
       return counter;
   }
   
   // Returns a 'binary string' (like. 001010111011100010) which is easy to do a hamming distance on. 
   public String getHash(InputStream is) throws Exception {
       BufferedImage img = ImageIO.read(is);
       
       /* 1. Reduce size. 
        * Like Average Hash, pHash starts with a small image. 
        * However, the image is larger than 8x8; 32x32 is a good size. 
        * This is really done to simplify the DCT computation and not 
        * because it is needed to reduce the high frequencies.
        */
       img = resize(img, size, size);
       
       /* 2. Reduce color. 
        * The image is reduced to a grayscale just to further simplify 
        * the number of computations.
        */
       img = grayscale(img);
       
       double[][] vals = new double[size][size];
       
       for (int x = 0; x < img.getWidth(); x++) {
           for (int y = 0; y < img.getHeight(); y++) {
               vals[x][y] = getBlue(img, x, y);
           }
       }
       
       /* 3. Compute the DCT. 
        * The DCT separates the image into a collection of frequencies 
        * and scalars. While JPEG uses an 8x8 DCT, this algorithm uses 
        * a 32x32 DCT.
        */
       long start = System.currentTimeMillis();
       double[][] dctVals = applyDCT(vals);
       System.out.println("DCT: " + (System.currentTimeMillis() - start));
       
       /* 4. Reduce the DCT. 
        * This is the magic step. While the DCT is 32x32, just keep the 
        * top-left 8x8. Those represent the lowest frequencies in the 
        * picture.
        */
       /* 5. Compute the average value. 
        * Like the Average Hash, compute the mean DCT value (using only 
        * the 8x8 DCT low-frequency values and excluding the first term 
        * since the DC coefficient can be significantly different from 
        * the other values and will throw off the average).
        */
       double total = 0;
       
       for (int x = 0; x < smallerSize; x++) {
           for (int y = 0; y < smallerSize; y++) {
               total += dctVals[x][y];
           }
       }
       total -= dctVals[0][0];
       
       double avg = total / (double) ((smallerSize * smallerSize) - 1);
   
       /* 6. Further reduce the DCT. 
        * This is the magic step. Set the 64 hash bits to 0 or 1 
        * depending on whether each of the 64 DCT values is above or 
        * below the average value. The result doesn't tell us the 
        * actual low frequencies; it just tells us the very-rough 
        * relative scale of the frequencies to the mean. The result 
        * will not vary as long as the overall structure of the image 
        * remains the same; this can survive gamma and color histogram 
        * adjustments without a problem.
        */
       String hash = "";
       
       for (int x = 0; x < smallerSize; x++) {
           for (int y = 0; y < smallerSize; y++) {
               if (x != 0 && y != 0) {
                   hash += (dctVals[x][y] > avg?"1":"0");
               }
           }
       }
       
       return hash;
   }
   
   private BufferedImage resize(BufferedImage image, int width,    int height) {
       BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
       Graphics2D g = resizedImage.createGraphics();
       g.drawImage(image, 0, 0, width, height, null);
       g.dispose();
       return resizedImage;
   }
   
   private ColorConvertOp colorConvert = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);

   private BufferedImage grayscale(BufferedImage img) {
       colorConvert.filter(img, img);
       return img;
   }
   
   private static int getBlue(BufferedImage img, int x, int y) {
       return (img.getRGB(x, y)) & 0xff;
   }
   
   // DCT function stolen from http://stackoverflow.com/questions/4240490/problems-with-dct-and-idct-algorithm-in-java

   private double[] c;
   private void initCoefficients() {
       c = new double[size];
       
       for (int i=1;i<size;i++) {
           c[i]=1;
       }
       c[0]=1/Math.sqrt(2.0);
   }
   
   private double[][] applyDCT(double[][] f) {
       int N = size;
       
       double[][] F = new double[N][N];
       for (int u=0;u<N;u++) {
         for (int v=0;v<N;v++) {
           double sum = 0.0;
           for (int i=0;i<N;i++) {
             for (int j=0;j<N;j++) {
               sum+=Math.cos(((2*i+1)/(2.0*N))*u*Math.PI)*Math.cos(((2*j+1)/(2.0*N))*v*Math.PI)*(f[i][j]);
             }
           }
           sum*=((c[u]*c[v])/4.0);
           F[u][v] = sum;
         }
       }
       return F;
   }

} 

